package com.ttai.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.ttai.R;
import com.ttai.dagger.componet.activity.DaggerEnterPageComponet;
import com.ttai.dagger.module.activity.EnterPagePresenterModule;
import com.ttai.presenter.activity.EnterPagePresenter;
import com.ttai.presenter.activity.InsertNewAcountPresenter;
import com.ttai.presenter.activity.InsertIdAcountPresenter;
import com.ttai.presenter.activity.InsertTipAcountPresenter;
import com.ttai.presenter.activity.LoginPresenter;
import com.ttai.ui.base.BaseActivity;
import com.ttai.untils.Constant;
import com.ttai.untils.getui.DemoIntentService;
import com.ttai.untils.getui.DemoPushService;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EnterPage extends BaseActivity {
    @Bind(R.id.et_enterphone)
    EditText etEnterphone;
    @Bind(R.id.et_entercode)
    EditText etEntercode;
    @Bind(R.id.btn_enter)
    Button btnEnter;
    @Bind(R.id.btn_enterpage)
    Button btnEnterpage;
    @Bind(R.id.btn_zhuce)
    Button btnZhuce;

    private long exitTime=0;
    public static String enterphonenumber="";
    public LoginPresenter loginPresenter;
    public String token;
    private static final int REQUEST_PERMISSION = 0;
    private Class userPushService = DemoPushService.class;



    /**
     * dagger注入
     */
    @Inject
    EnterPagePresenter enterPagePresenter;
    /**
     * 设置计时器
     */
    private CountDownTimer timer = new CountDownTimer(30000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            btnEnter.setEnabled(false);
            btnEnter.setText("休息"+(millisUntilFinished / 1000) + "秒");
        }

        @Override
        public void onFinish() {
            btnEnter.setEnabled(true);
            btnEnter.setText("获取验证码");
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enterpage);

        PackageManager pkgManager = getPackageManager();

        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
        }
        // 注册 intentService 后 PushDemoReceiver 无效, sdk 会使用 DemoIntentService 传递数据,
        // AndroidManifest 对应保留一个即可(如果注册 DemoIntentService, 可以去掉 PushDemoReceiver, 如果注册了
        // IntentService, 必须在 AndroidManifest 中声明)
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);

        Intent intent = new Intent(this,DemoIntentService.class);
        Intent intent1 = new Intent(this, DemoPushService.class);
        startService(intent);
        startService(intent1);

        ButterKnife.bind(this);
        setComponet();

        loginPresenter = new LoginPresenter(this);



    }
    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }

    @Override
    public void next(View view) {

    }

    @Override
    public void pre(View view) {

    }

    @Override
    public void setComponet() {
        DaggerEnterPageComponet.builder()
                .enterPagePresenterModule(new EnterPagePresenterModule(this))
                .build()
                .in(this);

    }

    @OnClick({R.id.btn_enter, R.id.btn_enterpage, R.id.btn_zhuce})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_enter:
                enterphonenumber=etEnterphone.getText().toString();
                /**
                 * 判断是否为手机号
                 */

                String mac=Constant.getMacAddress();

                if (!Constant.isMobile(enterphonenumber)){
                    Toast.makeText(EnterPage.this,"输入的手机号无效",Toast.LENGTH_SHORT).show();
                }
                else {
                    /**
                     * 启动计时器
                     */
                    timer.start();
                }
                enterPagePresenter.getVerifyCode(enterphonenumber,"1");
                break;
            case R.id.btn_enterpage:
                String scode = getScode(etEntercode.getText().toString()+enterPagePresenter.buildTime.getBuildtime());
                String clientId = PushManager.getInstance().getClientid(EnterPage.this);
                System.out.println("scode"+scode+" cid:"+clientId);
                try {
                    loginPresenter.getLoginInfo(enterphonenumber,scode,clientId);
                }catch (Exception e){
                    Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn_zhuce:
                Intent intent = new Intent(this,Register.class);
                startActivity(intent);
                break;
        }
    }
    /**
     * 连按两次退出程序
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

    private String getScode(String buildtime) {
        String scode = null;
        try {
           scode = Constant.mD5Code(buildtime);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return scode;
    }

//    public void storeNewAcount() {
//        token = Constant.getToken();
//        insertNewAcountPresenter.storeNewAcount(token);
//    }
//
//    public void storeTipAcount() {
//        token = Constant.getToken();
//        insertTipAcountPresenter.storeTipAcount(token);
//    }
//
//    public void restoreIdAcount() {
//        token = Constant.getToken();
//        insertIdAcountPresenter.storeIdAcount(token);
//    }
}
